package onlinebanking.security.probabilistic;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

import onlinebanking.math.GoldwasserMicali;

/**
 * 
 * @author Edgar
 *
 */
public class GMDecoder {

	private GMPrivateKey gmPrivateKey;
	private GoldwasserMicali gm;

	public GMDecoder(GMPrivateKey gmPrivateKey) {
		this.gmPrivateKey = gmPrivateKey;
		this.gm = new GoldwasserMicali();
	}

	public String decrypt(BigInteger[] ciphertext) {
		// p and q are private keys
		StringBuilder stringBuilder = new StringBuilder();
		BigInteger p = gmPrivateKey.getP();
		BigInteger q = gmPrivateKey.getQ();

		for (int i = 0; i < ciphertext.length; i++) {
			BigInteger c = new BigInteger(String.valueOf(ciphertext[i]));
			
			int l1 = gm.legendre(c, p);
			int l2 = gm.legendre(c, q);

			// DAPAT BOTH l1 and L2 equal to 1. and not l1*l2 ==1
			if (l1 == 1 && l2 == 1) {
				stringBuilder.append(0);
			} else {
				stringBuilder.append(1);
			}
		}
		String binaryMessage = stringBuilder.toString();
		return new String(new BigInteger(binaryMessage, 2).toByteArray());
	}

}
